<template>
  <el-dialog
    v-model="visible"
    v-if="load"
    title="批量修改重量尺寸"
    width="900px"
    draggable
    @close="close"
    :close-on-click-modal="false"
    :close-on-press-escape="false"
    :z-index="2000"
  >
    <el-form :model="formValues" label-position="top" ref="formRef" :rules="rules">
      <el-row :gutter="20">
        <el-col :span="8">
          <el-form-item label="产品毛重">
            <el-input
              class="w-full"
              v-model="formValues.gross_weight_g"
              oninput="value=value.replace(/[^\d.]/g, '').replace(/(\.\d{3}).+/, '$1').replace(/(\.\d{2})\d+/, '$1')"
              placeholder="请输入"
            >
              <template #append>g</template>
            </el-input>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="产品净重">
            <el-input
              class="w-full"
              v-model="formValues.net_weight_g"
              oninput="value=value.replace(/[^\d.]/g, '').replace(/(\.\d{3}).+/, '$1').replace(/(\.\d{2})\d+/, '$1')"
              placeholder="请输入"
            >
              <template #append>g</template>
            </el-input>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="包裹重">
            <el-input
              class="w-full"
              v-model="formValues.packing_weight_g"
              oninput="value=value.replace(/[^\d.]/g, '').replace(/(\.\d{3}).+/, '$1').replace(/(\.\d{2})\d+/, '$1')"
              placeholder="请输入"
            >
              <template #append>g</template></el-input
            >
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="产品包装尺寸/cm">
            <VGroup>
              <el-input
                style="width: 70px"
                v-model="formValues.packing_size_cm.length"
                placeholder="长"
                oninput="value=value.replace(/[^\d.]/g, '').replace(/(\.\d{3}).+/, '$1').replace(/(\.\d{2})\d+/, '$1')"
              ></el-input>
              <el-input
                style="width: 70px"
                v-model="formValues.packing_size_cm.width"
                placeholder="宽"
                oninput="value=value.replace(/[^\d.]/g, '').replace(/(\.\d{3}).+/, '$1').replace(/(\.\d{2})\d+/, '$1')"
              ></el-input>
              <el-input
                style="width: 135px"
                v-model="formValues.packing_size_cm.height"
                placeholder="高"
                oninput="value=value.replace(/[^\d.]/g, '').replace(/(\.\d{3}).+/, '$1').replace(/(\.\d{2})\d+/, '$1')"
              >
                <template #append>cm</template>
              </el-input>
            </VGroup>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="产品尺寸">
            <VGroup>
              <el-input
                style="width: 70px"
                v-model="formValues.product_size_cm.length"
                oninput="value=value.replace(/[^\d.]/g, '').replace(/(\.\d{3}).+/, '$1').replace(/(\.\d{2})\d+/, '$1')"
                :controls="false"
                placeholder="长"
              />
              <el-input
                style="width: 70px"
                v-model="formValues.product_size_cm.width"
                oninput="value=value.replace(/[^\d.]/g, '').replace(/(\.\d{3}).+/, '$1').replace(/(\.\d{2})\d+/, '$1')"
                :controls="false"
                placeholder="宽"
              />
              <el-input
                style="width: 135px"
                v-model="formValues.product_size_cm.height"
                oninput="value=value.replace(/[^\d.]/g, '').replace(/(\.\d{3}).+/, '$1').replace(/(\.\d{2})\d+/, '$1')"
                :controls="false"
                placeholder="高"
              >
                <template #append>cm</template>
              </el-input>
            </VGroup>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="整箱尺寸">
            <VGroup>
              <el-input
                style="width: 70px"
                v-model="formValues.packing_qty_size_cm.length"
                oninput="value=value.replace(/[^\d.]/g, '').replace(/(\.\d{3}).+/, '$1').replace(/(\.\d{2})\d+/, '$1')"
                :controls="false"
                placeholder="长"
              />
              <el-input
                style="width: 70px"
                v-model="formValues.packing_qty_size_cm.width"
                oninput="value=value.replace(/[^\d.]/g, '').replace(/(\.\d{3}).+/, '$1').replace(/(\.\d{2})\d+/, '$1')"
                :controls="false"
                placeholder="宽"
              />
              <el-input
                style="width: 135px"
                v-model="formValues.packing_qty_size_cm.height"
                oninput="value=value.replace(/[^\d.]/g, '').replace(/(\.\d{3}).+/, '$1').replace(/(\.\d{2})\d+/, '$1')"
                :controls="false"
                placeholder="高"
              >
                <template #append>cm</template>
              </el-input>
            </VGroup>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="整箱毛重">
            <el-input
              class="w-full"
              v-model="formValues.packing_gross_weight_kg"
              oninput="value.replace(/[^\d.]/g, '').replace(/(\.\d{3}).+/, '$1').replace(/(\.\d{2})\d+/, '$1')"
              placeholder="请输入"
            >
              <template #append
                ><span class="font-bold text-lg text-[#ff6334]">kg</span></template
              ></el-input
            >
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="装柜数量">
            <el-input
              class="w-full"
              v-model.number="formValues.cabinets_qty"
              oninput="value=value.replace(/[^0-9]/g,'')"
              placeholder="请输入"
            ></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="装箱数量">
            <el-input
              class="w-full"
              v-model="formValues.packing_qty"
              oninput="value=value.replace(/[^0-9]/g,'')"
              placeholder="请输入"
            ></el-input>
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>

    <template #footer>
      <div class="footer-btn">
        <el-button @click="close">取 消</el-button>
        <el-button type="primary" :loading="loading" @click="save">保 存</el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script setup>
import { ElMessage } from "element-plus";
import { batchUpdateWeightSize, getSKUAccessories } from "../api.js";
import { onMounted, reactive, toRefs } from "vue";

const visible = ref(false);
const loading = ref(false);
const formValues = ref({});
const formRef = ref();
const records = ref({});
const emit = defineEmits(["refresh"]);
const load = ref(false);
const open = async (data) => {
  if (!load.value) {
    load.value = true;
    await 1;
  }
  records.value = data;
  initForm();
  visible.value = true;
};

// 海外仓分类
const classified = [148, 224, 24, 1];

const initForm = async (data) => {
  formValues.value = {
    packing_size_cm: {
      length: "",
      width: "",
      height: "",
    },
    product_size_cm: {
      length: "",
      width: "",
      height: "",
    },
    packing_qty_size_cm: {
      length: "",
      width: "",
      height: "",
    },
  };
};

const save = async () => {
  const valid = await formRef.value.validate();
  if (!valid) return;
  const { length, width, height } = formValues.value.packing_size_cm;
  const classified_sku_ids = records.value.map((i) => {
    if (classified.includes(i.spu_category[0])) {
      return i.sku_ids;
    }
  });

  if (classified_sku_ids.length > 0 && (length || width || height)) {
    const dimensions = [length, width, height].sort((a, b) => a - b);
    if (!(dimensions[0] > 0 && dimensions[1] >= 10 && dimensions[2] >= 15)) {
      const is_satisfy = await checkSKUAccessories(classified_sku_ids);

      if (!is_satisfy) {
        ElMessage.warning(
          "海外仓SKU的包装尺寸或者绑定的辅料包装尺寸，至少有一边>=10cm;一边>=15cm且必须>0，当前SKU未满足，请核实；若有疑问可咨询物流部"
        );
        return;
      }
    }
  }

  loading.value = true;
  const sku_ids = records.value.map((i) => {
    return i.sku_ids;
  });
  try {
    const res = await batchUpdateWeightSize({ data: formValues.value, sku_ids });
    if (res.code === 200) {
      ElMessage.success("操作成功");
      close(true);
    }
  } catch (error) {
    console.log(error);
  } finally {
    loading.value = false;
  }
};

const close = async (refresh) => {
  records.value = [];
  initForm();
  await nextTick();
  await formRef.value.resetFields();
  if (refresh) emit("refresh");
  visible.value = false;
};
defineExpose({ open });

const rules = reactive({
  gross_weight_g: [{ required: true, message: "请输入产品毛重", trigger: "blur" }],
  net_weight_g: [{ required: true, message: "请输入产品净重", trigger: "blur" }],
});

const checkSKUAccessories = async (sku_ids) => {
  try {
    const res = await getSKUAccessories({ sku_ids });
    const is_satisfy = sku_ids.every((id) => {
      return res.data.some((i) => i.sku_id == id && isAvailable(i.accessories_goods_sku));
    });
    return is_satisfy;
  } catch (e) {
    throw Error(e);
  }
};

const isAvailable = (accessories_goods_sku) => {
  const { length, width, height } = accessories_goods_sku?.packing_size_cm;
  const dimensions = [length, width, height].sort((a, b) => a - b);
  if (dimensions[0] > 0 && dimensions[1] >= 10 && dimensions[2] >= 15) {
    return true;
  }
  return false;
};
</script>

<style lang="scss" scoped>
.footer-btn {
  :deep(.el-button + .el-button) {
    margin-left: 8px !important;
  }
}
</style>
